<template>
  <div class="video-player-container" @mousemove="handleMouseMove" @mouseleave="hideControls">
    <div class="video-wrapper" ref="videoWrapper">
      <video
        ref="videoElement"
        class="video-element"
        :src="src"
        @loadedmetadata="onLoadedMetadata"
        @timeupdate="onTimeUpdate"
        @ended="onEnded"
        @play="onPlay"
        @pause="onPause"
        @click="togglePlay"
        @dblclick="toggleFullscreen"
      />
      
      <!-- 播放/暂停按钮覆盖层 -->
      <div v-if="showPlayButton" class="play-overlay" @click="togglePlay">
        <div class="play-button">
          <el-icon v-if="!isPlaying" class="play-icon"><VideoPlay /></el-icon>
          <el-icon v-else class="pause-icon"><VideoPause /></el-icon>
        </div>
      </div>
      
      <!-- 加载指示器 -->
      <div v-if="isLoading" class="loading-overlay">
        <el-icon class="loading-icon"><Loading /></el-icon>
      </div>
      
      <!-- 控制栏 -->
      <div 
        class="controls-bar" 
        :class="{ 'controls-visible': showControls }"
        @mouseenter="showControls = true"
      >
        <!-- 进度条 -->
        <div class="progress-container" @click="seekTo">
          <div class="progress-track">
            <div class="progress-buffer" :style="{ width: `${bufferProgress}%` }"></div>
            <div class="progress-played" :style="{ width: `${playProgress}%` }"></div>
            <div 
              class="progress-thumb" 
              :style="{ left: `${playProgress}%` }"
              @mousedown="startDragging"
            ></div>
          </div>
          
          <!-- 时间提示 -->
          <div 
            v-if="hoverTime !== null" 
            class="time-tooltip" 
            :style="{ left: `${hoverPosition}px` }"
          >
            {{ formatTime(hoverTime) }}
          </div>
        </div>
        
        <!-- 控制按钮 -->
        <div class="controls-buttons">
          <div class="left-controls">
            <el-button type="text" @click="togglePlay" class="control-btn">
              <el-icon v-if="!isPlaying"><VideoPlay /></el-icon>
              <el-icon v-else><VideoPause /></el-icon>
            </el-button>
            
            <div class="volume-control">
              <el-button type="text" @click="toggleMute" class="control-btn">
                <el-icon v-if="isMuted || volume === 0"><Mute /></el-icon>
                <el-icon v-else>🔊</el-icon>
              </el-button>
              
              <div class="volume-slider" @mouseenter="showVolumeSlider = true" @mouseleave="showVolumeSlider = false">
                <el-slider
                  v-show="showVolumeSlider"
                  v-model="volume"
                  :min="0"
                  :max="1"
                  :step="0.01"
                  :show-tooltip="false"
                  @input="onVolumeChange"
                  vertical
                  height="80px"
                />
              </div>
            </div>
            
            <div class="time-display">
              <span>{{ formatTime(currentTime) }} / {{ formatTime(duration) }}</span>
            </div>
          </div>
          
          <div class="right-controls">
            <el-button type="text" @click="changePlaybackRate" class="control-btn">
              {{ playbackRate }}x
            </el-button>
            
            <el-button type="text" @click="togglePictureInPicture" class="control-btn">
              <el-icon><Monitor /></el-icon>
            </el-button>
            
            <el-button type="text" @click="toggleFullscreen" class="control-btn">
              <el-icon v-if="!isFullscreen"><FullScreen /></el-icon>
              <el-icon v-else><Aim /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import {
  VideoPlay,
  VideoPause,
  Loading,
  Mute,
  Monitor,
  FullScreen,
  Aim
} from '@element-plus/icons-vue';

const props = defineProps({
  src: {
    type: String,
    required: true
  },
  autoplay: {
    type: Boolean,
    default: false
  },
  muted: {
    type: Boolean,
    default: false
  },
  poster: {
    type: String,
    default: ''
  }
});

const emit = defineEmits(['play', 'pause', 'ended', 'timeupdate']);

// 引用
const videoElement = ref(null);
const videoWrapper = ref(null);

// 播放状态
const isPlaying = ref(false);
const isLoading = ref(false);
const currentTime = ref(0);
const duration = ref(0);
const volume = ref(1);
const isMuted = ref(props.muted);
const playbackRate = ref(1);

// 进度相关
const playProgress = ref(0);
const bufferProgress = ref(0);
const isDragging = ref(false);
const hoverTime = ref(null);
const hoverPosition = ref(0);

// 控制界面
const showControls = ref(false);
const showPlayButton = ref(true);
const showVolumeSlider = ref(false);
const isFullscreen = ref(false);

// 控制栏自动隐藏
let controlsTimer = null;

const showControlsTemporarily = () => {
  showControls.value = true;
  clearTimeout(controlsTimer);
  controlsTimer = setTimeout(() => {
    if (isPlaying.value) {
      showControls.value = false;
    }
  }, 3000);
};

const hideControls = () => {
  if (!isDragging.value) {
    showControls.value = false;
  }
};

const handleMouseMove = () => {
  showControlsTemporarily();
};

// 播放控制
const togglePlay = () => {
  if (videoElement.value) {
    if (isPlaying.value) {
      videoElement.value.pause();
    } else {
      videoElement.value.play();
    }
  }
};

const onPlay = () => {
  isPlaying.value = true;
  showPlayButton.value = false;
  emit('play');
};

const onPause = () => {
  isPlaying.value = false;
  showPlayButton.value = true;
  showControls.value = true;
  emit('pause');
};

const onEnded = () => {
  isPlaying.value = false;
  showPlayButton.value = true;
  showControls.value = true;
  emit('ended');
};

// 时间更新
const onTimeUpdate = () => {
  if (videoElement.value && !isDragging.value) {
    currentTime.value = videoElement.value.currentTime;
    playProgress.value = (currentTime.value / duration.value) * 100;
    emit('timeupdate', currentTime.value);
  }
};

const onLoadedMetadata = () => {
  if (videoElement.value) {
    duration.value = videoElement.value.duration;
    isLoading.value = false;
  }
};

// 进度条控制
const seekTo = (event) => {
  if (videoElement.value) {
    const rect = event.currentTarget.getBoundingClientRect();
    const percent = (event.clientX - rect.left) / rect.width;
    const time = percent * duration.value;
    videoElement.value.currentTime = time;
    currentTime.value = time;
    playProgress.value = percent * 100;
  }
};

const startDragging = (event) => {
  isDragging.value = true;
  showControls.value = true;
  
  const handleMouseMove = (e) => {
    if (isDragging.value && videoElement.value) {
      const rect = videoWrapper.value.querySelector('.progress-container').getBoundingClientRect();
      const percent = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
      const time = percent * duration.value;
      videoElement.value.currentTime = time;
      currentTime.value = time;
      playProgress.value = percent * 100;
    }
  };
  
  const handleMouseUp = () => {
    isDragging.value = false;
    document.removeEventListener('mousemove', handleMouseMove);
    document.removeEventListener('mouseup', handleMouseUp);
  };
  
  document.addEventListener('mousemove', handleMouseMove);
  document.addEventListener('mouseup', handleMouseUp);
};

// 音量控制
const toggleMute = () => {
  if (videoElement.value) {
    isMuted.value = !isMuted.value;
    videoElement.value.muted = isMuted.value;
  }
};

const onVolumeChange = (value) => {
  if (videoElement.value) {
    videoElement.value.volume = value;
    isMuted.value = value === 0;
  }
};

// 播放速度
const changePlaybackRate = () => {
  const rates = [0.5, 0.75, 1, 1.25, 1.5, 2];
  const currentIndex = rates.indexOf(playbackRate.value);
  const nextIndex = (currentIndex + 1) % rates.length;
  playbackRate.value = rates[nextIndex];
  
  if (videoElement.value) {
    videoElement.value.playbackRate = playbackRate.value;
  }
};

// 画中画
const togglePictureInPicture = async () => {
  if (videoElement.value) {
    try {
      if (document.pictureInPictureElement) {
        await document.exitPictureInPicture();
      } else {
        await videoElement.value.requestPictureInPicture();
      }
    } catch (error) {
      console.error('画中画模式切换失败:', error);
    }
  }
};

// 全屏
const toggleFullscreen = async () => {
  try {
    if (!document.fullscreenElement) {
      await videoWrapper.value.requestFullscreen();
      isFullscreen.value = true;
    } else {
      await document.exitFullscreen();
      isFullscreen.value = false;
    }
  } catch (error) {
    console.error('全屏切换失败:', error);
  }
};

// 格式化时间
const formatTime = (seconds) => {
  if (isNaN(seconds)) return '00:00';
  
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = Math.floor(seconds % 60);
  
  if (hours > 0) {
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  } else {
    return `${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  }
};

// 键盘快捷键
const handleKeydown = (event) => {
  if (!videoElement.value) return;
  
  switch (event.code) {
    case 'Space':
      event.preventDefault();
      togglePlay();
      break;
    case 'ArrowLeft':
      event.preventDefault();
      videoElement.value.currentTime = Math.max(0, videoElement.value.currentTime - 10);
      break;
    case 'ArrowRight':
      event.preventDefault();
      videoElement.value.currentTime = Math.min(duration.value, videoElement.value.currentTime + 10);
      break;
    case 'ArrowUp':
      event.preventDefault();
      volume.value = Math.min(1, volume.value + 0.1);
      onVolumeChange(volume.value);
      break;
    case 'ArrowDown':
      event.preventDefault();
      volume.value = Math.max(0, volume.value - 0.1);
      onVolumeChange(volume.value);
      break;
    case 'KeyM':
      event.preventDefault();
      toggleMute();
      break;
    case 'KeyF':
      event.preventDefault();
      toggleFullscreen();
      break;
  }
};

// 监听全屏变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement;
};

onMounted(() => {
  if (videoElement.value) {
    videoElement.value.volume = volume.value;
    videoElement.value.muted = isMuted.value;
    
    if (props.autoplay) {
      videoElement.value.play();
    }
  }
  
  document.addEventListener('keydown', handleKeydown);
  document.addEventListener('fullscreenchange', handleFullscreenChange);
});

onUnmounted(() => {
  document.removeEventListener('keydown', handleKeydown);
  document.removeEventListener('fullscreenchange', handleFullscreenChange);
  clearTimeout(controlsTimer);
});

// 监听音量变化
watch(volume, (newVolume) => {
  if (videoElement.value) {
    videoElement.value.volume = newVolume;
  }
});
</script>

<style lang="less" scoped>
.video-player-container {
  position: relative;
  width: 100%;
  background: #000;
  border-radius: 8px;
  overflow: hidden;

  .video-wrapper {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 56.25%; // 16:9 aspect ratio

    .video-element {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      object-fit: contain;
      cursor: pointer;
    }

    .play-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(0, 0, 0, 0.3);
      cursor: pointer;
      transition: opacity 0.3s ease;

      .play-button {
        width: 80px;
        height: 80px;
        background: rgba(255, 255, 255, 0.9);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;

        &:hover {
          background: rgba(255, 255, 255, 1);
          transform: scale(1.1);
        }

        .play-icon,
        .pause-icon {
          font-size: 32px;
          color: #333;
        }
      }
    }

    .loading-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(0, 0, 0, 0.5);

      .loading-icon {
        font-size: 32px;
        color: white;
        animation: spin 1s linear infinite;
      }
    }

    .controls-bar {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      background: linear-gradient(transparent, rgba(0, 0, 0, 0.8));
      padding: 20px 16px 16px;
      transform: translateY(100%);
      transition: transform 0.3s ease;

      &.controls-visible {
        transform: translateY(0);
      }

      .progress-container {
        position: relative;
        margin-bottom: 12px;
        cursor: pointer;

        .progress-track {
          height: 4px;
          background: rgba(255, 255, 255, 0.3);
          border-radius: 2px;
          position: relative;

          .progress-buffer {
            height: 100%;
            background: rgba(255, 255, 255, 0.5);
            border-radius: 2px;
            transition: width 0.1s ease;
          }

          .progress-played {
            position: absolute;
            top: 0;
            left: 0;
            height: 100%;
            background: #409eff;
            border-radius: 2px;
            transition: width 0.1s ease;
          }

          .progress-thumb {
            position: absolute;
            top: 50%;
            width: 12px;
            height: 12px;
            background: #409eff;
            border-radius: 50%;
            transform: translate(-50%, -50%);
            cursor: pointer;
            opacity: 0;
            transition: opacity 0.3s ease;
          }
        }

        &:hover .progress-thumb {
          opacity: 1;
        }

        .time-tooltip {
          position: absolute;
          bottom: 20px;
          background: rgba(0, 0, 0, 0.8);
          color: white;
          padding: 4px 8px;
          border-radius: 4px;
          font-size: 12px;
          transform: translateX(-50%);
          pointer-events: none;
        }
      }

      .controls-buttons {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .left-controls,
        .right-controls {
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .control-btn {
          color: white;
          font-size: 18px;
          padding: 8px;

          &:hover {
            background: rgba(255, 255, 255, 0.1);
          }
        }

        .volume-control {
          position: relative;

          .volume-slider {
            position: absolute;
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
            margin-bottom: 8px;
            background: rgba(0, 0, 0, 0.8);
            padding: 8px;
            border-radius: 4px;
          }
        }

        .time-display {
          color: white;
          font-size: 14px;
          margin-left: 8px;
        }
      }
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 全屏样式
:global(.video-player-container:fullscreen) {
  .video-wrapper {
    height: 100vh;
    padding-bottom: 0;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .video-player-container {
    .controls-bar {
      padding: 16px 12px 12px;

      .controls-buttons {
        .left-controls,
        .right-controls {
          gap: 4px;
        }

        .control-btn {
          font-size: 16px;
          padding: 6px;
        }

        .time-display {
          font-size: 12px;
        }
      }
    }

    .play-overlay .play-button {
      width: 60px;
      height: 60px;

      .play-icon,
      .pause-icon {
        font-size: 24px;
      }
    }
  }
}
</style>
